package com.umeox.watch.audiobooks.utils

import android.text.TextUtils
import com.umeox.watch.audiobooks.db.AppDatabase
import com.yc.music.config.MusicConstant
import com.yc.music.model.AudioBean
import com.yc.music.utils.MusicSpUtils

/**
 * 上次播放的音频文件名称
 */
const val SP_KEY_MUSIC_NAME = "musicName"

/**
 * 收藏列表SP key
 */
const val SP_KEY_FAVORITE_STORY = "storyFavorite"

/**
 * 列表请求码
 */
const val FAVORITE_LIST_REQUEST_CODE = 1000

/**
 * 音频列表选中回调的Intent Key
 * 列表类型
 * 用于歌曲循环时 采用哪个列表循环
 */
const val INTENT_KEY_LIST_TYPE = "musicListType"

/**
 * 音频列表选中回调的Intent Key
 * 音频名称
 * 用于定位选中的是哪首歌曲
 */
const val INTENT_KEY_AUDIO_ID = "playId"

/**
 * 所有故事列表
 */
const val LIST_TYPE_ALL = 1000

/**
 * 收藏列表
 */
const val LIST_TYPE_FAVORITE = 2000

/**
 * 热门列表
 */
const val LIST_TYPE_HOT = 3000


/**
 * 古兰经音频管理器
 */
object StoryManager {

    /**
     * 热门故事列表
     */
    val hotStoryList = mutableListOf<AudioBean>()

    /**
     * 所有故事列表
     */
    val allStoryList = mutableListOf<AudioBean>()

    /**
     * 收藏列表
     */
    val favoriteList = mutableListOf<AudioBean>()

    /**
     * 收藏列表名称
     */
    val favoriteNameList =
        MusicSpUtils.getInstance(MusicConstant.SP_NAME).getString(SP_KEY_FAVORITE_STORY, "")
            .split(",").toMutableList()

    fun setFavorite(audioBean: AudioBean): Boolean {
        val result = if (favoriteNameList.contains(audioBean.id)) {
            favoriteNameList.remove(audioBean.id)
            favoriteList.remove(audioBean)
            false
        } else {
            favoriteNameList.add(audioBean.id)
            favoriteList.add(audioBean)
            true
        }

        MusicSpUtils.getInstance(MusicConstant.SP_NAME)
            .put(SP_KEY_FAVORITE_STORY, favoriteNameList.joinToString(","))
        return result
    }

    fun buildFavoriteList(){
        val allStoryList = AppDatabase.get().allStoryDao().loadAll()//[1,2,3,4,5,6]
        val ids = mutableListOf<Long>()
        favoriteNameList.filter { !TextUtils.isEmpty(it) }.forEach {
            ids.add(it.toLong())
        }
        val filterStoryList = allStoryList.filter { it.id in ids }
        for ((id, name, coverUrl, author, storyUrl, storyLength) in filterStoryList) {
            val audioBook = AudioBean()
            audioBook.id = id.toString()
            audioBook.title = name
            audioBook.artist = author
            audioBook.coverPath = coverUrl
            audioBook.path = storyUrl
            audioBook.duration = storyLength * 1000L
            favoriteList.add(audioBook)
        }
    }
}
